iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
Software Development

clojure 30 days系列 第 23

clojure 30 days - day 21

  • 分享至 

  • xImage
  •  

Problem Description

Complete the solution so that it splits the string into pairs of two characters.
If the string contains an odd number of characters then it should replace the missing
second character of the final pair with an underscore ('_').

Examples:

'abc' => ['ab', 'c_']
'abcdef' => ['ab', 'cd', 'ef']

Note

Keywords:

  • count: gets length of string
  • odd?: checks if number is odd
  • str: concatenates strings (adds underscore if needed)
  • *partition: splits collection into groups of specified size
  • map: applies function to each element
  • apply str: joins characters in each pair back into strings
  • ->>: threading macro for cleaner data transformation

Implementation

; implement
(defn solution [s]
  (let [padded-string (if (odd? (count s))
                        (str s "_")
                        s)]
    (->> padded-string
         (partition 2)
         (map #(apply str %)))))
         ; test
; execute implement function
(defn tester [arg exp]
  (= (solution arg) exp))

; args & exception
(comment
  (tester "abc" ["ab" "c_"])
  (tester "abcdef" ["ab" "cd" "ef"])
  (tester "" [])
  (tester "x" ["x_"])
  (tester "Banana" ["Ba" "na" "na"])
  (tester "CodeWars" ["Co" "de" "Wa" "rs"]))



上一篇
clojure 30 days - day 20
下一篇
clojure 30 days - day 22
系列文
clojure 30 days25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言